package cn.talk.socket.controller;

import cn.talk.socket.service.Client;
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class TController {

    Map<String, Client> clientMap = new HashMap<>();

    @Resource
    StringRedisTemplate stringRedisTemplate;

    //创建连接（登录操作）
    @RequestMapping(value = "CrateOne")
    public String CrateOne(Integer id) throws IOException, InterruptedException {
        Client client = new Client();
        Thread.sleep(1000);
        //由redis缓存进行存储ClientID
        stringRedisTemplate.opsForValue().set("SocketID:" + id, client.getId());
        clientMap.put(client.getId(), client);
        for (String name : clientMap.keySet()) {
            System.out.println(name);
        }
        return JSON.toJSONString(true);
    }

    //发送实时消息
    @RequestMapping(value = "Sent")
    public String Sent(String resourceId,String message,String sendId) throws IOException, InterruptedException {
        String clientResourceID = stringRedisTemplate.opsForValue().get("SocketID:" + resourceId);
        Client client = clientMap.get(clientResourceID);
        if (stringRedisTemplate.hasKey("SocketID:" + sendId)){
            String clientSentId =  stringRedisTemplate.opsForValue().get("SocketID:" + sendId);
            client.send(clientSentId,message);
            return JSON.toJSONString(true);
        }else {
            return "用户未上线";
        }
    }

    //发送离线消息
    //可以使用MySQL，redis进行缓存，然后在用户执行登录时进行拉取

    //获取消息接口
    @RequestMapping(value = "pullMessage")
    public String pullMessage(String id){
        String clientResourceID = stringRedisTemplate.opsForValue().get("SocketID:" + id);
        Client client = clientMap.get(clientResourceID);
        Map<String,Object> result = new HashMap<>();
        result.put("you",clientResourceID);
        try {
            result.put("message",client.messageList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return JSON.toJSONString(result);
    }

    //登出操作
    @RequestMapping(value = "loginOut")
    public String loginOut(String id) throws IOException {
        String clientResourceID = stringRedisTemplate.opsForValue().get("SocketID:" + id);
        Client client = clientMap.get(clientResourceID);
        client.send(id,"loginOut");
        stringRedisTemplate.delete("SocketID:" + id);
        return JSON.toJSONString(true);
    }
}
